import { GetQiniuUploadToken } from '@/services/api';
import { getBase64 } from '@/utils';
import { PlusOutlined, UploadOutlined } from '@ant-design/icons';
import { Button, Modal, Upload, message } from 'antd';
import { UploadChangeParam, UploadFile } from 'antd/lib/upload';
import { useEffect, useState } from 'react';

let flag = false; //验证图片格式大小满足不满足要求,如果不满足清空fileList

const handleUpload = async (options: any) => {
  const { file, onSuccess } = options;

  const res = await GetQiniuUploadToken();
  const token = res.data.token;
  const fmData = new FormData();
  fmData.append('file', file);
  fmData.append('token', token); // multiple

  const response = await fetch(res.data.host, {
    method: 'POST',
    body: fmData,
  });
  const data = await response.json();
  console.log(data);
  onSuccess(data);
};
/*
 *图片上传组件,
 *接收参数
 * num 限定图片数量,number类型
 * listType 上传列表的内建样式，支持三种基本样式 text, picture 和 picture-card,默认 text,string类型
 * name 发到后台的文件参数名,默认 file,string类型
 * url 上传地址,,string类型
 * data 上传所需额外参数,object|(file) => object
 * */

const UploadImgs = (props: any) => {
  const {
    num,
    listType,
    data,
    onChange,
    size = 5,
    name = 'file',
    value = [],
  } = props;

  const [visible, updateVisible] = useState(false); //预览图片弹窗
  const [image, updateImage] = useState(''); //预览图片
  const [files, updateFiles] = useState<UploadFile<any>[]>([]);
  //预览图片
  const handlePreview = async (file: any) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }
    updateVisible(true);
    updateImage(file.url || file.preview);
  };
  /**
   * 上传中、完成、失败都会调用这个函数。
   * file 当前操作的文件对象,fileList 当前的文件列表 img 列表
   * status 文件上传状态 ,状态有：uploading(上传中) done(上传完成) error(上传失败) removed(移除)
   * response: 服务端响应内容
   * */
  const handleChange = ({
    file,
    fileList,
  }: UploadChangeParam<UploadFile<any>>) => {
    console.log(':::::file', file, fileList, flag);
    updateFiles([...fileList]); //必须更新fileList,才能监听status状态
    let list: any[] = [];
    if (flag) {
      //存在条件不满足情形处理
      fileList.splice(fileList.length - 1, 1);
      updateFiles(fileList);
      flag = false; //复原flag
    } else {
      //删除处理
      if (file.status === 'removed') {
        if (fileList.length === 0) {
          list = [];
        } else {
          list = fileList;
        }
        if (onChange) {
          onChange(list);
        }
      }
      //上传完成处理
      if (file.status === 'done') {
        for (let i = 0; i < fileList.length; i++) {
          if (fileList[i].response) {
            const data = fileList[i].response;
            // console.log(data)
            const url = data && data.url ? data.url : ''; //文件路径
            const name = data && data.origin ? data.origin : ''; //文件名
            if (url && typeof url === 'string') {
              list.push({
                url,
                name,
                uid: fileList[i].uid || '',
                status: fileList[i].status || '',
              });
            } else {
              message.error(fileList[i].response.msg || '上传失败~');
            }
          } else if (fileList[i].url && typeof fileList[i].url === 'string') {
            //已经上传了的重新加入
            list.push(fileList[i]);
          }
        }
        updateFiles(list);
        if (onChange) onChange(list);
      }
    }
  };
  //限制图片 格式、size
  const handleBeforeUpload = (file: any) => {
    const isJPG = file.type === 'image/jpg';
    const isJPEG = file.type === 'image/jpeg';
    const isPNG = file.type === 'image/png';
    const isLtSize = file.size / 1024 / 1024 < size;
    if (!(isJPG || isJPEG || isPNG)) {
      message.warning('只能上传JPG 、JPEG、 PNG格式的图片~');
      flag = true;
      return false;
    } else if (!isLtSize) {
      message.warning(`图片大小不能超过${size}M~`);
      flag = true;
      return false;
    } else {
      flag = false;
      return (isJPG || isJPEG || isPNG) && isLtSize;
    }
  };
  //回显
  useEffect(() => {
    if (Array.isArray(value) && value.length > 0) {
      const files: UploadFile[] = [];
      for (let i = 0; i < value.length; i++) {
        const time = new Date().getTime();
        files.push({
          uid: i + time + '',
          name: i + time + '',
          status: 'done',
          url: value[i].url,
        });
      }
      updateFiles(files);
    }
    if (typeof value === 'string' && value) {
      const files: UploadFile[] = [];
      files.push({
        uid: new Date().getTime() + '',
        name: new Date().getTime() + '',
        status: 'done',
        url: value,
      });
      updateFiles(files);
    }
  }, [value]); //eslint-disable-line react-hooks/exhaustive-deps
  return (
    <div id="upload">
      <Upload
        customRequest={handleUpload}
        data={data ? data : null}
        listType={
          listType === 'picture-card'
            ? 'picture-card'
            : listType === 'text'
            ? 'text'
            : 'picture'
        }
        fileList={files}
        name={name} //	发到后台的文件参数名
        onPreview={handlePreview} // 点击图片缩略图，进行预览
        beforeUpload={handleBeforeUpload} // 上传之前，对图片的格式做校验
        onChange={handleChange} // 每次上传图片时，都会触发这个方法
      >
        {files.length >= num ? null : listType === 'picture-card' ? (
          <PlusOutlined style={{ fontSize: 30 }} />
        ) : (
          <Button icon={<UploadOutlined />}>上传图片</Button>
        )}
      </Upload>
      <Modal
        open={visible}
        footer={null}
        closable={false}
        onCancel={() => updateVisible(false)}
      >
        <img alt="example" style={{ width: '100%' }} src={image} />
      </Modal>
    </div>
  );
};
export default UploadImgs;
